package com.elitel.frame.business.controller;


import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.elitel.common.exception.BaseException;
import com.elitel.frame.base.component.RedisCacheComponent;
import com.elitel.frame.base.component.RedisCacheTreeConfig;
import com.elitel.frame.base.service.CfgExtsqlService;
import com.elitel.frame.base.service.DBServerService;
import com.elitel.frame.base.service.TreeConfigFileService;
import com.elitel.frame.business.service.CensusSearchService;
import com.elitel.frame.business.service.ExecuteSqlService;
import com.elitel.frame.business.service.TableFieldCommService;
import com.elitel.frame.business.service.TreeConfigService;
import com.elitel.frame.main.entity.BaseTreeconfig;
import com.elitel.frame.main.entity.CfgDb;
import com.elitel.frame.main.entity.CfgExtsql;
import com.elitel.frame.main.entity.CfgExttree;
import com.elitel.frame.main.entity.ext.DBServer;
import com.elitel.frame.main.entity.vo.JsonDataResult;
import com.elitel.frame.main.entity.vo.PageResponseVo;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * @ClassName: ExecuteSqlController 
 * @Description: 执行sql端
 * @author Fanwenquan 
 * @date 2017年8月2日 下午2:03:39
 */
@Controller
@RequestMapping("/business/execute")
@Api(value = "/business/execute", tags = "资源树服务接口")
public class TreeConfigFiledController {
	
		private static final Logger logger = LoggerFactory.getLogger(TreeConfigFiledController.class);

		
		private CfgDb cfgDb;
		
		@Autowired
		private ExecuteSqlService executeSqlService;
		
		@Autowired
		private CfgExtsqlService cfgExtsqlService;
		
		@Autowired
		private RedisCacheComponent redisCacheComponent;
		
		@Resource
		private  DBServerService dbServerServiceImpl;
		
		@Resource
		private TreeConfigService treeConfigServiceImpl;
		
		@Resource
		private TreeConfigFileService treeConfigFileServiceImpl;
		
		@Resource
		private CensusSearchService censusSearchServiceImpl;
		
		@Resource
		private RedisCacheTreeConfig redisCacheTreeConfig;
		
		@Resource
		private TableFieldCommService tableFieldCommServiceImpl;
		
		//获取资源树是否采用慢加载
		@ApiOperation(notes = "/lodingorno", httpMethod = "GET", value = "根据服务编码获取资源树是否采用慢加载")
		@RequestMapping("/lodingorno")
		@ResponseBody
		@ApiImplicitParams({ 
			@ApiImplicitParam(name="serviceID", value="服务编码", required=true, dataType="String", paramType="query")
		})
		public boolean getLoading(HttpServletRequest request,@RequestParam(value = "serviceID") String serviceID){
			String guid = serviceID;
			boolean  xx = false;
			CfgExttree cfgExttree = treeConfigFileServiceImpl.getOneCfgExttree(guid);
			if(Integer.parseInt(String.valueOf(cfgExttree.getIslazyload()))==1){
				xx=true;
			}
			return xx;
		}
		
		//获取查询条件的集合
		@ApiOperation(notes = "/selectTreeColumn", httpMethod = "GET", value = "根据服务编码获取资源树查询条件的集合")
		@RequestMapping("/selectTreeColumn")
		@ResponseBody
		@ApiImplicitParams({ 
			@ApiImplicitParam(name="serviceID", value="服务编码", required=true, dataType="String", paramType="query")
		})
		public Object selectTreeColumn(HttpServletRequest request,@RequestParam(value = "serviceID") String serviceID){
			String guid = serviceID;
			String debug = request.getParameter("debug");
			List<Map<String, String>> list2 = new ArrayList<>();
			JsonDataResult jsonDataResult = new JsonDataResult();
			try {
				List<BaseTreeconfig> list = treeConfigFileServiceImpl.selectTreeConfigList(guid);
				CfgExttree cfgExttree = treeConfigFileServiceImpl.getOneCfgExttree(guid);
				Map<String, String> fileMap = new HashMap<>();
				for(BaseTreeconfig baseTreeconfig:list){
					CfgDb cfgDb = treeConfigFileServiceImpl.selectCfgDb(cfgExttree.getDtDbKey());
					List<Map<String, String>> list3 = tableFieldCommServiceImpl.getTableQueryField(cfgDb, guid, 3, String.valueOf(baseTreeconfig.getGrade()));
					for(Map<String, String> map:list3){
						if (map.get("fieldnamecn")!=null&&map.get("fieldname")!=null) {
							if (fileMap.get(map.get("fieldname"))==null||!map.get("fieldnamecn").equals(fileMap.get(map.get("fieldname")))) {
								list2.add(map);
								fileMap.put(map.get("fieldname"), map.get("fieldnamecn"));
							}
						}
					}
				}
				jsonDataResult.setData(list2);
				jsonDataResult.setMessage("查询成功");
				jsonDataResult.setResult(0);
			} catch (BaseException e) {
				jsonDataResult.setMessage(e.getExceptionVO().getDesc());
				jsonDataResult.setResult(Integer.valueOf(e.getExceptionVO().getValue()));
			}			
			
			return jsonDataResult;
		}
		//获取资源树数据
		@ApiOperation(notes = "/selectTreeConfig", httpMethod = "GET", value = "根据服务编码查询资源树信息")
		@RequestMapping("/selectTreeConfig")
		@ResponseBody
		@ApiImplicitParams({ 
			@ApiImplicitParam(name="serviceID", value="服务编码", required=true, dataType="String", paramType="query"),
			@ApiImplicitParam(name="debug", value="是否校验", required=false, dataType="boolean", paramType="query"),
			@ApiImplicitParam(name="conQuery", value="查询条件集合", required=false, dataType="String", paramType="query")
		})
		public Object selectTreeConfig(@RequestParam(value = "serviceID") String serviceID, String debugs ,String conQuery){
			String guid = serviceID;
			String debug = debugs;
			//String sessionid = request.getSession().getId();
			String conquery = conQuery;
			JsonDataResult jsonDataResult = new JsonDataResult();
			CfgExttree cfgExttree = treeConfigFileServiceImpl.selectTreeFile(guid);
			cfgDb = redisCacheTreeConfig.selectCfgDbOne(cfgExttree.getDtDbKey());
			Object object  = null;
			//Arrays.asList( "a", "b", "d" ).
			try {
				object = treeConfigServiceImpl.selectTreeConfigFile(cfgDb,guid, conquery);
				jsonDataResult.setData(object);
				jsonDataResult.setMessage("查询成功");
				jsonDataResult.setResult(0);
			} catch (BaseException e) {
				jsonDataResult.setMessage(e.getExceptionVO().getDesc());
				jsonDataResult.setResult(Integer.valueOf(e.getExceptionVO().getValue()));
			}
//			if (debug!=null||"true".equals(debug)) {
//				return FileWriterUtil.txt2String(sessionid);
//			}else{
				//return object;
				return jsonDataResult;
//			}
		}
	
		//根据guid grade 获取资源树数据
		@ApiOperation(notes = "/getPartTreeConfig", httpMethod = "GET", value = "根据guid grade 获取资源树数据")
		@RequestMapping("/getPartTreeConfig")
		@ResponseBody
		@ApiImplicitParams({ 
			@ApiImplicitParam(name="serviceID", value="服务编码", required=true, dataType="String", paramType="query"),
			@ApiImplicitParam(name="grade", value="层级数", required=false, dataType="String", paramType="query"),
			@ApiImplicitParam(name="id", value="当前层级id", required=false, dataType="String", paramType="query"),
			@ApiImplicitParam(name="conQuery", value="查询条件集合", required=false, dataType="String", paramType="query")
		})
		public Object getTreeConfig(HttpServletRequest request,@RequestParam(value = "serviceID") String serviceID,String grade,String id,String conQuery){
			String conquery = conQuery;
			String sessionid = request.getSession().getId();
			JsonDataResult jsonDataResult = new JsonDataResult();
			Object object  = null;
			CfgExttree cfgExttree = treeConfigFileServiceImpl.getOneCfgExttree(serviceID);
			CfgDb cfgDb = redisCacheTreeConfig.selectCfgDbOne(cfgExttree.getDtDbKey());
			try {
				object= treeConfigServiceImpl.getPartTreeConfig(cfgDb,id,serviceID,grade,conquery);
				jsonDataResult.setData(object);
				jsonDataResult.setMessage("查询成功");
				jsonDataResult.setResult(0);
			} catch (BaseException e) {
				jsonDataResult.setMessage(e.getExceptionVO().getDesc());
				jsonDataResult.setResult(Integer.valueOf(e.getExceptionVO().getValue()));
			}
//			if (debug!=null||"true".equals(debug)) {
//				return FileWriterUtil.txt2String(sessionid);
//			}else{
				return jsonDataResult;
			//}
		}
				


		//数据服务是否缓存
		@ApiOperation(notes = "/selectIsPaging", httpMethod = "GET", value = "根据服务编码获取资源树查询条件的集合")
		@RequestMapping("/selectIsPaging")
		@ResponseBody
		@ApiImplicitParams({ 
			@ApiImplicitParam(name="serviceID", value="服务编码", required=true, dataType="String", paramType="query")
		})
		public boolean selectIsPaging(HttpServletRequest request,@RequestParam(value = "serviceID") String serviceID){
			String guid = serviceID;
			DBServer dBServer = dbServerServiceImpl.selectServerOnes(guid);
			boolean ispaging = false;
			if (dBServer.getCatched()==1) {
				ispaging = true;
			}
			return ispaging;
		}

	/**
	 * 	
	 * @Title: executeSqlMethod 
	 * @Description: TODO(传参调用sql执行返回结果) 
	 * @author Fanwenquan
	 * @return Object
	 * @throws
	 */
	@ApiOperation(notes = "/executeQuery", httpMethod = "GET", value = "传参调用sql执行返回结果")
	@RequestMapping("/executeQuery")
	@ResponseBody
	@ApiImplicitParams({ 
		@ApiImplicitParam(name="serviceID", value="服务编码", required=true, dataType="String", paramType="query"),
		@ApiImplicitParam(name="pageNO", value="当前页码", required=false, dataType="String", paramType="query"),
		@ApiImplicitParam(name="pageSize", value="每页条数", required=false, dataType="String", paramType="query"),
		@ApiImplicitParam(name="conQuery", value="查询条件集合", required=false, dataType="String", paramType="query")
	})
	public Object executeSqlMethod(@RequestParam(value = "serviceID")String serviceID, String pageNO, String pageSize, String conQuery ) {
		if(pageNO == null || "".equals(pageNO)){
			pageNO = "1";
		}
		if(pageSize == null || "".equals(pageSize)){
			pageSize = "10";
		}
		PageResponseVo<Map<String, Object>>  pageResponse = null;
		try {
			CfgExtsql cfgExtsql = cfgExtsqlService.selectCfgSqlByPrimary(serviceID);
			CfgDb cfgDB = redisCacheComponent.cfgDBRedisCache(cfgExtsql.getDtDbKey());
			if(null != cfgExtsql.getIspagination() && cfgExtsql.getIspagination() == 1){
			pageResponse = executeSqlService.executequerySqlPagination(cfgDB, serviceID, pageNO, pageSize, conQuery, cfgExtsql);
			}else if (null != cfgExtsql.getIspagination() && cfgExtsql.getIspagination() == 0){
				pageResponse = executeSqlService.executequerySql(cfgDB, serviceID, conQuery, cfgExtsql);	
			}
		} catch (Exception e) {
			logger.error("传参调用sql执行错误：", e);
		}
		
		
		return pageResponse;
	}
	
	/**
	 * <pre>processSqlByFreemarker(freemarker处理sql)   
	 * @author：FanWenquan    
	 * @date：2017年8月31日 上午10:34:17   
	 * @param sql
	 * @param root
	 * @return</pre>
	 */
	private String processSqlByFreemarker(String sql, Map root) {
		String str="";
		Configuration cfg = new Configuration();  
        StringTemplateLoader stringLoader = new StringTemplateLoader();  
        stringLoader.putTemplate("myTemplate",sql);  
        cfg.setTemplateLoader(stringLoader);  
        try {  
            Template template = cfg.getTemplate("myTemplate","utf-8");  
            StringWriter writer = new StringWriter();    
            template.process(root, writer);  
            str = writer.toString();
        } catch (IOException e) { 
            e.printStackTrace();  
        }catch (TemplateException e) {  
            e.printStackTrace();  
        }
		return str;
	}
	

}
